Chapter 1: Python Basics 1
From book Python Programming (Problem solving, Packages and Libraries) published by McGraw Hill Education (India) Private limited.
By:
Note the following:-
>>> symbol and therefore cannot be directly executed. If you want to execute them on IDLE or Jupyter, you need to manually remove the >>> symbol.At some places, to improve readability, page numbers of the book are indicated in green font like:- See Page 181 of the book
This document was first created as a Jupyter Notebook as combination of Markdown and code cells (extension .ipynb) and then downloaded as html. If someone wants to "modify" or "extend' this document, you may ask for the original .ipynb file by sending me an e-mail at:- 999.anuraggupta@gmail.com
1.3.8. Using Python Interactive mode as a calculator
You can use the Python interpreter as a calculator. As you type in mathematical expressions, results are displayed on pressing “return”. The operators +, -, * and / (For addition, subtraction, multiplication and division) work just like in many popular programming languages. You can use parenthesis ie “()” for grouping.
Hash i.e. # is used for single-line comments and totally ignored by the Python interpreter. (Anything from beginning of hash, #, to the end of the line is treated as a comment).
Use of Python interactive mode as a calculator is shown below. (Comments using hash, #, have been added to help understand the syntax of Python)
>>># Comments in Python begin with # (hash) and are ignored by the interpreter
>>>2+4 # Addition
6
>>>2*4 # Multiplication
8
>>>2**4 # 2 raised to power 4
16
>>>2/4 # 2 divided by 4
0.5
1.4.1. Using simple print statement in Python 2.x (which is print() function in 3.x)
You can give a print command with text to IDLE and the Python interpreter will output the text.
Please note that in Python 2.x print was a statement while in Python 3.x, print() is a function.
Functions are dealt with later but for the present it is sufficient to know that in Python, a function call is followed by parenthesis ie (). In Python 3.x you have to wrap the object that you want to print in parenthesis:-
# ---ON IDLE---
1.4.3. Single line Comments and multi-line comments
In Python, the hash (#) symbol indicates the beginning of a comment and the comment extends to the “newline or return”.
So, hash comments are one- line comments.
Comments are for understanding the script.
If your comment extends over more than one line, then one way of doing it is to begin each comment line with a hash (#), as shown below:-
# ---ON IDLE---
#This is a comment which extends over two lines..... this is line 1
#... This is line 2
Another way of creating multi-line comments is to use triple quotes, that is, either ''' or """. Note that triple quotes can be used for “multi-line comments” as well as “multi-line strings”, as follows:-
>>>""" Multiline quote
... continues
.... ends"""
>>>
1.5.1. Explicit line continuation
In Python, the newline character (i.e. carriage return) marks the end of a statement. But you can use the continuation character (\) to extend a statement over multiple lines. This is explicit line continuation and the “back slash” character ie (\) is the “line continuation” character in Python.
# ---ON IDLE---
>>>2+3\
+4
9
1.5.2. Implicit multiline statement
Line continuation in Python, is implicit (i.e. implied) inside brackets [ ], parentheses ( ) and braces { }.
The following code gives examples of implicit line continuation:
# ---ON IDLE---
>>> fruit = ['mango', 'grape', #List of fruits
'apple']
>>> alphabet = ('a', 'b', # Tuple of alphabet
'c', 'd')
>>> opposites = { # Dictionary of opposites
'tall': 'short',
'fat': 'slim',
}
1.5.3. Multiple statements in single line using semicolons
In Python, you can put multiple statements in a single line, using semicolons, as follows:
(But this is not good programming practice since it makes the program difficult to read.)
# ---ON IDLE---
>>> a=5;b=6;print(a+b)
11
1.6.1. Python keywords and Identifiers
You can see the complete list of keywords on IDLE as follows:-
# ---ON IDLE---
>>># To see list of all keywords, type the following two commands
>>>import keyword # FIRST Command. Imports module keyword
>>> keyword.kwlist # SECOND Command
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
1.6.4. Assignment
Note that the assignment of a data (such as string, integer, float, and so on) to a variable is different in C++ and in Python.
In C++, the assignment of a data to a variable first creates a place in memory, which you can think of as a box. Once such a “box” is created, then data may be placed in the box.
However, assignment of a value to a variable in Python is different. Suppose you have the following assignment statements in Python:-
# ---ON IDLE---
>>> x = 2 # x "points" to 2
>>> y = x # Now y also "points" to 2
>>> y = 3 # Now y "points" to 3
>>>print(x)
2
>>>print(y)
3
>>>
Note that the variable, that is, “tag” does not have a type but the data (to which the tag is attached to), has a “type”.
Hence, it is possible to assign a “value” of one type to a variable and then assign it “value” of another “type”. You are allowed to make more than one assignment to the same variable.
A fresh assignment makes the existing variable refer to a new value (and stop referring to the old value).
For instance:
# ---ON IDLE---
>>>x = ‘abc’
>>> type(x) # type() function is used to get type of an object
<class'str'>
>>> x=5
>>> type(x)
<class'int'>
In Python, it is not the ‘tag’ or the variable name which is cast. Rather, it is the object to which this tag points to, which is cast.
For instance, casting of a float into an int (Note that in Python, int stands for integer data type) will remove the fractional part, that is, the decimal part of the float number as follows:-
# ---ON IDLE---
>>> myFloat = 78.11
>>> id(myFloat)
32319904
>>> myInt = int(myFloat) # int() is a casting function
>>>myInt # myInt will now point to value 78
78
>>> id(myInt)
1398392032
>>> id(78) # Note id(78) same as id(myInt)
1398392032
1.6.5. Reference in Python
1.6.6. Shared reference
1.6.7. Variable vs. identifier
(These topics are not covered since they require detailed explanation, which are given in the book.)